package com.eqxiu.ieditor.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.eqxiu.ieditor.commons.web.ResultData;

import eqxiu.passport.sdk.dto.UserDTO;
import eqxiu.passport.sdk.user.Passports;

@Component
public class PermissionInterceptor implements HandlerInterceptor {

	protected Logger logger = LoggerFactory.getLogger(getClass());
	
	@Value("${userinfo.url}")
	private String userInfoURL;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		if ("options".equalsIgnoreCase(request.getMethod())) {
			return true;
		}

		UserDTO user = Passports.getUserInfo(request, userInfoURL);
		if (user == null || !user.available()) {
			response.setContentType("application/json;charset=utf8");
			response.getWriter().write(JSON.toJSONString(new ResultData().setCode(403).setSuccess(false).setMsg("user not valid or disabled")));;
			return false;
		}
		
		UserContext.setUser(user);
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

	}

}
